package com.yuezhi.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuezhi.acl.entity.SysRole;
import com.yuezhi.acl.entity.SysUserRole;
import com.yuezhi.acl.mapper.SysRoleMapper;
import com.yuezhi.acl.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuezhi.acl.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author boys
 * @since 2020-12-16
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysUserRoleService userRoleService;

    @Override
    public Map<String, Object> findRoleByUserId(String userId) {
        //查询所有角色
        List<SysRole> allRoles = baseMapper.selectList(null);
        //根据用户id，查询用户拥有的角色id
        List<SysUserRole> existUserRoleList = userRoleService.list(new QueryWrapper<SysUserRole>().eq("user_id", userId).select("role_id"));
        List<String> existRoleList = existUserRoleList.stream().map(c -> c.getRoleId()).collect(Collectors.toList());
        List<SysRole> assignRoles = new ArrayList<>();
        for (SysRole role : allRoles) {
            //已分配
            if (existRoleList.contains(role.getId())) {
                assignRoles.add(role);
            }
        }
        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("assignRoles", assignRoles);
        roleMap.put("allRoles", allRoles);
        return roleMap;
    }

    //根据用户分配角色
    @Override
    public void assignRolesByUser(String userId, String[] roleId) {
        userRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        List<SysUserRole> userRoleList = new ArrayList<>();
        for (String r : roleId) {
            if (StringUtils.isEmpty(r)) continue;
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(r);
            userRoleList.add(userRole);
        }
        userRoleService.saveBatch(userRoleList);
    }

    @Override
    public List<SysRole> selectRoleByUserId(String id) {
        List<SysUserRole> userRoleList = userRoleService.list(new QueryWrapper<SysUserRole>().eq("user_id", id).select("role_id"));
        List<String> collect = userRoleList.stream().map(item -> item.getRoleId()).collect(Collectors.toList());
        List<SysRole> roleList = new ArrayList<>();
        if(collect.size()>0){
            roleList = baseMapper.selectBatchIds(collect);
        }
        return roleList;
    }
}
